var _canvas = null;
var _context = null;

var _format = null;
var _file = null;
var _status = null;


var _image = null;
var _imageSrc = null;
var _imageData = null;


$(document).ready(function()
{
	var height_window;
	if (typeof window.innerWidth != 'undefined')
	{
		height_window =window.innerHeight;
	}
	else
	{
		height_window = document.documentElement.clientHeight;
	}

	$('#navigation').attr('style','height:'+ (height_window-105) +'px;');
	$('#content').attr('style','height:'+ (height_window-100) +'px;');
	$('#mid').attr('style','height:'+ (height_window-125) +'px;');
	//Hide (Collapse) the toggle containers on load
	$('.toggle_navigation').hide(); 
	

	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
	$('h2.category_navigation').click(function()
	{
		$(this).next().slideToggle('fast');
		return false; //Prevent the browser jump to the link anchor
	});
	
	initialize();
	checkFileAPI();
	
});

function initialize() 
{
	_status = document.getElementById('status');
	_canvas = document.getElementById('canvasMain');
	_context = _canvas.getContext('2d');
	clearCanvas();
}

function clearCanvas() 
{
	_context.fillStyle = '#999999';
	_context.fillRect(0, 0, _canvas.width, _canvas.height);	
}

function filesOnChange(evt) 
{
	//evt.preventDefault();
	//_file = evt.target.files[0];
	
	_file = evt.files[0];
	var reader = new FileReader();

	reader.onload = function (event) 
	{
		console.log(event.target.result);
		openFile(event.target.result);
	};


	reader.readAsDataURL(_file);
	
	return false;
}

function checkFileAPI()
{
	if (Utilities.checkFileAPIs() == false)  
	{
		_status.className = 'fail';
	} 
	else 
	{
		_status.className = 'success';
		_status.innerHTML = 'File API & FileReader available';
	}
}

function openFile(src)
{
	_imageSrc = src;
	if (_imageSrc == null)
		_imageSrc = 'image/snowflake.jpg';
	
	reload();
}

function saveFile()
{
	$("#canvasMain").hide();
	$("#canvasImg").show();
	
    var dataURL = _canvas.toDataURL(_format);

    document.getElementById("canvasImg").src = dataURL;
    
    _status.className = 'success';
	_status.innerHTML = 'Right click image and choose Save image as ...';
}

function reload()
{
	$("#canvasMain").show();
	$("#canvasImg").hide();
	
	_image = new Image();
	_image.src = _imageSrc;
	
	_image.onload = function()
	{
		_imageData = Filters.getPixels(_image);
		
		clearCanvas();
		Utilities.setImageToCanvas('canvasMain', _imageData, true);
		var count = Filters.countColors(_imageData);
		
		_format = _image.src.substring(_image.src.indexOf("data:") + 5, _image.src.indexOf(";"));
		
		_status.className = 'success';
		_status.innerHTML = 'Image format: ' + _format + ' Number of colors is: ' + count;
	};
}
